import axios from 'axios';
axios.jsonp = (url) => {
  if (!url) {
    return;
  }
  return new Promise((resolve) => {
    const callbackId = '__JSONP__' + Date.now();
    window[callbackId] = (result) => {
      resolve(result);
    };
    var JSONP = document.createElement('script');
    JSONP.type = 'text/javascript';
    url = url.replace(/\?/, `?jsoncallback=${callbackId}&`);
    JSONP.src = url + '&_' + Date.now();
    document.getElementsByTagName('head')[0].appendChild(JSONP);
    setTimeout(() => {
      document.getElementsByTagName('head')[0].removeChild(JSONP);
    }, 500);
  });
};

// import qs from 'qs';
/* eslint-disable no-undef */
/* eslint-disable camelcase */
var defaultPortNb = 50876; // 默认端口
var alternatePort = 50877; // 备用端口
// eslint-disable-next-line camelcase
var g_portNb = defaultPortNb; // eslint-disable-next-line camelcase
var g_input_connectFlag = 0; // 密码服务是否初始化成功
// eslint-disable-next-line camelcase
var g_sign_connectFlag = 0; // 签名服务是否初始化成功
// eslint-disable-next-line camelcase
var g_stopSendRequest = 0; // 光标是否在输入框内
// eslint-disable-next-line camelcase
var g_connectTimes = 0; // 初始化连接失败次数
var WIN_32_ACTIVEX_VERSION = 2003009023; // Windows系统下32位控件版本号
var WIN_64_ACTIVEX_VERSION = 2003009023; // Windows系统下64位控件版本号
var WIN_PLUGIN_VERSION = 2003009023; // Windows系统下插件版本号
// var WIN_POWERSERVICE_VERSION = 19011018000; //Windows系统下本地服务版本号
var WIN_POWERSERVICE_VERSION = 20004018000; // Windows系统下本地服务版本号
var MAC_PLUGIN_VERSION = 0; // Mac系统下插件版本号
var WIN_SETUP_PATH = 'http://csiihf.tpddns.net:9000/download/PowerEnterCSII.exe'; // Windows系统下安装程序下载路径
var MAC_SETUP_PATH = ''; // Mac系统下安装程序下载路径
var LocalObjVersion = '';
var passType = '';
var encPass = '';
var certlist = ''; // 证书列表
var certValue = ''; // SM2证书信息
var certSN = ''; // 证书SN
var serviceSignCert = ''; // 证书base64值
var serviceSignData = ''; // 签名数据（密文）
const HASH_ALG = 'sm2'; // 算法类型
// 加密平台国密公钥(生产)
var encSM2Publickey =
  'C4DFF3C3372E7DD217E22E6A44406E46760F58180440012CF819E25DEDADBEA48FF037D30E61E829BA0F36892D041DA64D320E3AE094C7D3DAF6AAB22B37DDC7';
// 安全输入控件
var PassClsid = 'clsid:3B77F9DD-DCD3-42C2-A351-5A6E7EBEAF6F';
var UtilClsid = 'clsid:5B9E2AE6-86D8-4951-909B-D469C5D84500';
var CtlName = 'OWERENTERBOSR.PowerUtilityXBOSRCtrl.1';
var getSM2input;
var createinput;
// 安全输入插件
// eslint-disable-next-line camelcase
var PowerEnter_MIME = 'application/x-vnd-csii-powerenter-demo';
// eslint-disable-next-line camelcase
var PowerEnter_ProductDescription = 'PowerEnter Plug-in for BOSR';

// 数字签名控件
var SignClsid = 'CLSID:0DCDED8D-ABA9-4624-B2C1-E3A2E30E4DF4';

// 数字签名插件
// eslint-disable-next-line camelcase
var PowerSign_MIME = 'application/x-vnd-csii-powersign-bosr';
// eslint-disable-next-line no-unused-vars
var PowerSign_ProductDescription = 'PowerSign Plug-in for BOSR';
var startParam = 'pageID=testPage&editID=testPass&minLen=1&maxLen=2&encryptType=0&appKeyIndex=1';
// vue 对象
var vmObj = {};

// 控件默认属性
function powerConfig(args) {
  var defaults = {
    width: 240,
    height: 30,
    maxLength: 20,
    minLength: 6,
    maskChar: '*',
    backColor: '#FFFFFF',
    textColor: '#0000FF',
    borderColor: '#FFFFFF',
    accepts: '[:graph:]+',
    caption: '企业网银标准版',
    captionColor: '#87011f',
    captionFont: '',
    captionSize: 0,
    captionBold: 'true',
    lang: 'zh_CN',
    softKeyboard: 'true',
    softkbdRandom: 'true',
    nextId: '',
    adjustTime: 'false',
    wmode: 'transparent',
  };
  for (var p in args) {
    if (args[p] != null) defaults[p] = args[p];
  }
  return defaults;
}

// 高版本默认属性
function powerProter(arr) {
  var defaults = {
    width: 240,
    height: 30,
    maxLength: 20,
    minLength: 6,
    accepts: '[:graph:]+',
    page: 'loginPage',
    placeholder: '请输入6到20位密码',
    id: new Date().getTime(),
    showDegree: false,
    pwdDegree: '',
    init: false,
    pwdHtml: '',
    nextId: '',
    pwdCyclic: false, // 只在多密码框下使用默认false
  };
  for (var e in arr) {
    var args = arr[e];
    // eslint-disable-next-line no-undef
    var def = Object.assign({}, defaults, args);
    arr[e] = def;
  }

  return arr;
}
function init(dtd) {
  GetResponseDataByDtd(true, defaultPortNb, 'initDll', startParam, dtd);
  GetResponseDataByDtd(true, alternatePort, 'initDll', startParam, dtd);
  return dtd;
}
/**
 * 创建密码控件
 */
// eslint-disable-next-line no-unused-vars
function createPwdObject(vm) {
  window.startParam = startParam;
  vmObj = vm;
  if (!vm.pwdObj) {
    return;
  }
  vm.pwdObj = powerProter(vm.pwdObj);

  // 判断是否是高版本浏览器
  if (!isSupportBrowser()) {
    // eslint-disable-next-line no-undef
    var dtd = defer();
    // init(dtd);
    // eslint-disable-next-line no-undef
    Promise.all([init(dtd)]);
    createinput = function() {
      if (g_input_connectFlag == 1) {
        for (var i = 0; i < vm.pwdObj.length; i++) {
          if (!vm.pwdObj[i].init) {
            vm.pwdObj[i].pwdHtml = '';
            continue;
          }
          var strPlaceholder = vm.pwdObj[i].placeholder;
          var powerpass = vm.pwdObj[i].id;
          var page = vm.pwdObj[i].page;
          var result = getLocalService(
            page,
            powerpass,
            vm.pwdObj[i].minLength,
            vm.pwdObj[i].maxLength,
            0,
            vm.pwdObj[i].accepts,
            1,
            29,
            '',
            0,
            encSM2Publickey,
            strPlaceholder,
            0,
            1,
            vm.pwdObj[i],
          );
          vm.pwdObj[i].pwdHtml = result;
          var script2 = document.createElement('script');
          script2.language = 'javascript';
          script2.innerHTML =
            ' document.getElementById(' +
            vm.pwdObj[i].id +
            ').onkeydown = function(event) {' +
            'console.log(event.keyCode);' +
            'if (event.keyCode == "' +
            9 +
            '" && document.getElementById == "' +
            vm.pwdObj[i].id +
            '") {' +
            'document.getElementById("' +
            vm.pwdObj[i].id +
            '").focus()' +
            '}';
          // eslint-disable-next-line no-unused-expressions
          ('});');
          result.script2 = script2;
        }
      } else if (g_input_connectFlag == 2) {
        var DownloadPath = getDownLoadPath();
        var tempHtml1 = '<a href=' + DownloadPath + ' class="download_install">点击此处更新控件</a>';
        // eslint-disable-next-line no-redeclare
        for (var i = 0; i < vm.pwdObj.length; i++) {
          // eslint-disable-next-line no-redeclare
          var result = {
            input: tempHtml1,
            script: '',
          };
          vm.pwdObj[i].pwdHtml = result;
        }
      } else {
        // eslint-disable-next-line no-redeclare
        var DownloadPath = getDownLoadPath();
        // eslint-disable-next-line no-redeclare
        var tempHtml1 = '<a href=' + DownloadPath + ' class="download_install">点击此处下载控件</a>';
        // eslint-disable-next-line no-redeclare
        for (var i = 0; i < vm.pwdObj.length; i++) {
          // eslint-disable-next-line no-redeclare
          var result = {
            input: tempHtml1,
            script: '',
          };
          vm.pwdObj[i].pwdHtml = result;
        }
      }
      // 强制刷新 渲染
      vm.$forceUpdate();
    };
  } else {
    for (var i = 0; i < vm.pwdObj.length; i++) {
      if (!vm.pwdObj[i].init) {
        vm.pwdObj[i].pwdHtml = '';
        continue;
      }
      var pwdObj = vm.pwdObj[i];
      var powerpass = pwdObj.id;
      var html = getPassObject(powerpass, {
        width: pwdObj.width,
        height: pwdObj.height,
        maxLength: pwdObj.maxLength,
        minLength: pwdObj.minLength,
        accepts: pwdObj.accepts,
      });
      var result = {
        input: html,
        script: '',
      };

      // 判断是否是ie
      if (!isIE()) {
        var script = document.createElement('script');
        script.language = 'javascript';
        script.innerHTML = 'doAdd(' + powerpass + ');';
        result.script = script;
      } else {
        if (vm.pwdObj[i].showDegree) {
          // eslint-disable-next-line no-redeclare
          var script = document.createElement('script');
          script.language = 'javascript';
          script.setAttribute('for', vm.pwdObj[i].id);
          script.event = 'EventDegree(arg1)';
          script.innerHTML =
            'var obj = document.getElementById(' +
            vm.pwdObj[i].id +
            ').parentNode.parentNode.nextElementSibling;' +
            'var child = obj.children' +
            'var degree = "";' +
            'console.log(arg1);' +
            'if (arg1 == "W") {' +
            'obj.style.display = inline-block' +
            'degree = "弱";' +
            'child[0]classList.add("vx-pwd-inten-w").classList.remove("vx-pwd-inten-m").classList.remove("vx-pwd-inten-s");' +
            'child[1].classList.remove("vx-pwd-inten-w").classList.remove("vx-pwd-inten-m").classList.remove("vx-pwd-inten-s");' +
            'child[2].classList.remove("vx-pwd-inten-w").classList.remove("vx-pwd-inten-m").classList.remove("vx-pwd-inten-s");' +
            '}' +
            'else if (arg1 == "M") {' +
            'obj.style.display = inline-block;' +
            'degree = "中";' +
            'child[0].classList.remove("vx-pwd-inten-w").classList.add("vx-pwd-inten-m").classList.remove("vx-pwd-inten-s");' +
            'child[1].classList.remove("vx-pwd-inten-w").classList.add("vx-pwd-inten-m").classList.remove("vx-pwd-inten-s");' +
            'child[2].classList.remove("vx-pwd-inten-w").classList.remove("vx-pwd-inten-m").classList.remove("vx-pwd-inten-s");' +
            '}' +
            'else if (arg1 == "S") {' +
            'obj.style.display = inline-block;' +
            'degree = "强";' +
            'child[0].classList.remove("vx-pwd-inten-w").classList.remove("vx-pwd-inten-m").classList.add("vx-pwd-inten-s");' +
            'child[1].classList.remove("vx-pwd-inten-w").classList.remove("vx-pwd-inten-m").classList.add("vx-pwd-inten-s");' +
            'child[2].classList.remove("vx-pwd-inten-w").classList.remove("vx-pwd-inten-m").classList.add("vx-pwd-inten-s");' +
            '}else{' +
            'degree = "";' +
            'child[0].classList.remove("vx-pwd-inten-w").classList.remove("vx-pwd-inten-m").classList.remove("vx-pwd-inten-s");' +
            'child[1].classList.remove("vx-pwd-inten-w").classList.remove("vx-pwd-inten-m").classList.remove("vx-pwd-inten-s");' +
            'child[2].classList.remove("vx-pwd-inten-w").classList.remove("vx-pwd-inten-m").classList.remove("vx-pwd-inten-s");' +
            'obj.style.display = none' +
            '}' +
            'console.log(degree)';
          result.script = script;
        }
        if (vm.pwdObj[i].nextId != '') {
          var script2 = document.createElement('script');
          script2.language = 'javascript';
          script2.setAttribute('for', vm.pwdObj[i].id);
          script2.event = 'EventTab';
          script2.innerHTML = 'document.getElementById("' + vm.pwdObj[i].nextId + '").focus();';
          result.script2 = script2;
        }
      }
      vm.pwdObj[i].pwdHtml = result;
    }
    // 强制刷新
    vm.$forceUpdate();
  }

  // 签名服务
  if (!isSupportBrowser()) {
    // eslint-disable-next-line no-redeclare
    let dtd = defer();
    let certStoreType = 1; // 0:个人证书   1: 个人证书及国密证书
    let certStoreName = 'CSIIBANK'; // 国密证书自定义store名称
    let startParam = 'certStoreType=' + certStoreType + '&certStoreName=' + certStoreName;
    Promise.all([
      GetResponseDataByDtd(true, defaultPortNb, 'initPSDll', startParam, dtd),
      GetResponseDataByDtd(true, alternatePort, 'initPSDll', startParam, dtd),
    ]).then(function() {
      if (g_sign_connectFlag == 1) {
        // console.log("签名服务初始化成功");
      } else if (g_sign_connectFlag == 2) {
        // console.log("签名服务初始化成功,但需要更新");
      } else {
        // console.log("签名服务初始化失败");
      }
    });
  } else {
    var tempHtml1 = getSignObject('powersign');
    document.getElementById('SIGNSPAN').innerHTML = tempHtml1;
  }
}

/**
 * 比较密码是否相等
 */
// eslint-disable-next-line no-unused-vars
function passwordCheck(pwd1, pwd2, callBack) {
  var result = {
    equal: false,
  };
  if (!isSupportBrowser()) {
    var dtd = defer();
    Promise.all([CheckServicePass(pwd1.page, pwd1.id, pwd2.page, pwd2.id, dtd)]).then(function() {
      setTimeout(() => {
        if (passType == '0') {
          // console.log("两次密码一致。");
          result.equal = true;
        } else {
          // console.log("两次密码不一致。");
          result.equal = false;
        }
        passType = '';
        callBack(result);
      }, 500);
    });
  } else {
    var powerobj1 = document.getElementById(pwd1.id);
    var powerobj2 = document.getElementById(pwd2.id);
    if (powerobj1.getMeasureValue() == powerobj2.getMeasureValue()) {
      result.equal = true;
    } else {
      result.equal = false;
    }
    callBack(result);
  }
}
function writePluginObject(oid, clsid, cfg) {
  document.write(
    '<object id="' +
      oid +
      '" type="' +
      clsid +
      '" width="' +
      cfg.width +
      '" height="' +
      cfg.height +
      '" style="width:' +
      cfg.width +
      'px;height:' +
      cfg.height +
      'px">',
  );
  for (var name in cfg) {
    document.write('<param name="' + name + '" value="' + cfg[name] + '">');
  }
  document.write('</object>');
}

function writeObject(oid, clsid, cfg) {
  document.write('<object id="' + oid + '" classid="' + clsid + '" width="' + cfg.width + '" height="' + cfg.height + '">');
  for (var name in cfg) {
    document.write('<param name="' + name + '" value="' + cfg[name] + '">');
  }
  document.write('</object>');
}

function PEGetPluginObject(oid, clsid, cfg) {
  var tempHtml =
    '<object id="' +
    oid +
    '" type="' +
    clsid +
    '" width="' +
    cfg.width +
    '" height="' +
    cfg.height +
    '" style="width:' +
    cfg.width +
    'px;height:' +
    cfg.height +
    'px">';
  for (var name in cfg) {
    tempHtml += '<param name="' + name + '" value="' + cfg[name] + '">';
  }
  tempHtml += '</object>';
  return tempHtml;
}

function PEGetObject(oid, clsid, cfg) {
  var tempHtml = '<object id="' + oid + '" classid="' + clsid + '" width="' + cfg.width + '" height="' + cfg.height + '">';
  for (var name in cfg) {
    tempHtml += '<param name="' + name + '" value="' + cfg[name] + '">';
  }
  tempHtml += '</object>';
  return tempHtml;
}

function getPassObject(oid, cfg) {
  if (!oid || typeof oid !== 'string') {
    alert('getPassObject Failed: oid is required!');
    return '';
  } else {
    var tempPassHtml = getPEXSetupUrl(oid);
    if (tempPassHtml == '') {
      if (isIE()) {
        tempPassHtml = PEGetObject(oid, PassClsid, powerConfig(cfg));
      } else {
        tempPassHtml = PEGetPluginObject(oid, PowerEnter_MIME, powerConfig(cfg));
      }
    }
    return tempPassHtml;
  }
}

// eslint-disable-next-line no-unused-vars
function getUtilObject(oid, cfg) {
  if (!oid || typeof oid !== 'string') {
    alert('getUtilObject Failed: oid is required!');
    return '';
  } else {
    var tempUtilHtml = '';
    if (isIE()) {
      tempUtilHtml = PEGetObject(oid, UtilClsid, powerConfig(cfg));
    } else {
      tempUtilHtml = PEGetPluginObject(oid, PowerEnter_MIME, powerConfig(cfg));
    }
    return tempUtilHtml;
  }
}

function getSignObject(oid) {
  if (!oid || typeof oid !== 'string') {
    alert('getSignObject Failed: oid is required!');
    return '';
  } else {
    var tempSignHtml = '';
    if (isIE()) {
      tempSignHtml = '<object id="' + oid + '" classid="' + SignClsid + '" width="1" height="1"></object>';
    } else {
      tempSignHtml = '<object id="' + oid + '" type="' + PowerSign_MIME + '" width="1" height="1"></object>';
    }
    return tempSignHtml;
  }
}

function writeUtilObject(oid, cfg) {
  if (!oid || typeof oid !== 'string') {
    alert('writePassObj Failed: oid are required!');
  } else {
    if (isIE()) {
      writeObject(oid, UtilClsid, powerConfig(cfg));
    } else {
      writePluginObject(oid, PowerEnter_MIME, powerConfig(cfg));
    }
  }
}

// eslint-disable-next-line no-unused-vars
function getPassInput(obj, ts, massage, DoPostFun) {
  var result = {
    error: '',
    password: '',
    id: obj.id,
  };

  try {
    if (!isSupportBrowser()) {
      var dtd = defer();

      Promise.all([GetPassword(obj.page, obj.id, ts, dtd)]);
      getSM2input = function() {
        if (encPass < 0) {
          var error;
          if (encPass == -1) {
            error = '内容不能为空';
          } else if (encPass == -2) {
            error = '输入长度不足';
          } else if (encPass == -3) {
            error = '输入内容不合规';
          } else if (encPass == -6) {
            error = '输入内容不包含字母和数字';
          } else {
            error = '未知错误';
          }
          result.error = massage + error;
          result[obj.id] = false;
          // PEGetElement(spanId).innerHTML = massage +error;
          DoPostFun(result);
        } else {
          result.password = encPass;
          result[obj.id] = true;
          DoPostFun(result);
        }
      };
      encPass = '';
    } else {
      var powerobj = document.getElementById(obj.id);
      powerobj.setTimestamp(ts + '');
      powerobj.sm2PublicKey(encSM2Publickey);
      var nresult = powerobj.verify();

      if (nresult < 0) {
        var error;
        if (nresult == -1) {
          error = '内容不能为空';
        } else if (nresult == -2) {
          error = '输入长度不足';
        } else if (nresult == -3) {
          error = '输入内容不合规';
        } else if (nresult == -6) {
          error = '输入内容不包含字母和数字';
        } else {
          error = powerobj.lastError();
        }
        result.error = massage + error;
        result[obj.id] = false;
        // PEGetElement(spanId).innerHTML = massage +error;
        DoPostFun(result);
      } else {
        if (obj.calcFactor == '0') {
          value = powerobj.getValue();
        } else {
          value = powerobj.getPinValue();
        }
        if (value == '') {
          result.error = massage + powerobj.lastError();
          result[obj.id] = false;
          // PEGetElement(spanId).innerHTML= massage+powerobj.lastError();
          // return result;
          DoPostFun(result);
        } else {
          result.password = value;
          result[obj.id] = true;
          DoPostFun(result);
        }
      }
    }
  } catch (e) {
    result.error = '控件尚未安装，请下载并安装控件！';
    // PEGetElement(spanId).innerHTML= "控件尚未安装，请下载并安装控件！:";
    DoPostFun(result);
  }
}
// eslint-disable-next-line no-unused-vars
function getMFMInput(id, ts, spanId, massage, DoPostFun) {
  try {
    if (!isSupportBrowser()) {
      var dtd = defer();
      // eslint-disable-next-line no-unused-vars
      var getSM2input;
      Promise.all([GetServiceMFM('loginPage', id, ts, dtd)]).then(function() {
        getMFMinput();
      });
      getMFMinput = function() {
        if (encMFM < 0) {
          var error = '未知错误';
          PEGetElement(spanId).innerHTML = massage + error;
          return;
        }
        DoPostFun(encMFM);
      };
    } else {
      var powerobj = document.getElementById(id);
      powerobj.setTimestamp(ts);
      value = powerobj.getMFM();
      if (value == '') {
        PEGetElement(spanId).innerHTML = massage + powerobj.lastError();
        return null;
      } else {
        DoPostFun(value);
      }
    }
  } catch (e) {
    PEGetElement(spanId).innerHTML = '控件尚未安装，请下载并安装控件！';
  }

  return null;
}

function CheckServicePass(pageID1, editID1, pageID2, editID2, dtd) {
  var startParam = 'pageID1=' + pageID1 + '&editID1=' + editID1 + '&pageID2=' + pageID2 + '&editID2=' + editID2;
  GetResponseDataByDtd(true, g_portNb, 'comparePassword', startParam, dtd);
  return dtd;
}
function GetPassword(pageID, editID, ts, dtd) {
  var startParam = 'pageID=' + pageID + '&editID=' + editID + '&ts=' + ts;
  GetResponseDataByDtd(true, g_portNb, 'getValue', startParam, dtd);
  return dtd;
}

function GetServiceMFM(pageID, editID, ts, dtd) {
  var startParam = 'pageID=' + pageID + '&editID=' + editID + '&ts=' + ts;

  GetResponseDataByDtd(true, g_portNb, 'getMFM', startParam, dtd);
  return dtd;
}

// eslint-disable-next-line no-unused-vars
function GetServiceCertList(dtd) {
  GetResponseDataByDtd(false, g_portNb, 'GetCertList', '', dtd);
  return dtd;
}

// eslint-disable-next-line no-unused-vars
function GetServiceSignCert(certSN, hashAlg, dtd) {
  var startParam = 'cn=' + certSN + '&alg=' + hashAlg;
  GetResponseDataByDtd(false, g_portNb, 'GetSignCert', startParam, dtd);
  return dtd;
}

// eslint-disable-next-line no-unused-vars
function GetServiceSignData(certSN, hashAlg, massageData, dtd) {
  var startParam = 'signData=' + massageData + '&alg=' + hashAlg + '&cn=' + certSN;
  GetResponseDataByDtd(false, g_portNb, 'GetSignData', startParam, dtd);
  return dtd;
}

// eslint-disable-next-line no-unused-vars
function GetServiceLastError(dtd) {
  GetResponseDataByDtd(false, g_portNb, 'GetLastError', '', dtd);
  return dtd;
}

function PEGetElement(id) {
  return window.document.getElementById(id);
}

function getPEXSetupUrl(oid) {
  var DownloadPath = getDownLoadPath();
  var ObjVersion = getObjVersion();
  var tempSetupUrl = '';
  if (isRegisteredPowerEnter() == false) {
    if (
      navigator.platform == 'Win32' ||
      navigator.platform == 'Windows' ||
      navigator.platform == 'Win64' ||
      navigator.platform == 'Mac68K' ||
      navigator.platform == 'MacPPC' ||
      navigator.platform == 'Macintosh' ||
      navigator.platform == 'MacIntel'
    ) {
      tempSetupUrl = '<a href="' + DownloadPath + '" id="' + oid + '" class="download_install">点击此处下载控件</a>';
    } else {
      tempSetupUrl = '<a href="#" id="' + oid + '" class="download_install">暂不支持此系统</a>';
    }
  } else {
    var LocalObjVersion = getLocalObjVersion();
    if (LocalObjVersion < ObjVersion) {
      tempSetupUrl = '<a href="' + DownloadPath + '" id="' + oid + '" class="download_install">点击此处更新控件</a>';
    }
  }
  return tempSetupUrl;
}

function getLocalObjVersion() {
  if (LocalObjVersion == '') {
    try {
      LocalObjVersion = PEGetElement('versionObj').getVersion();
    } catch (e) {
      LocalObjVersion = getObjVersion();
    }
  }
  return LocalObjVersion;
}

writeUtilObject('versionObj', {
  width: 1,
  height: 1,
});
function isRegisteredPowerEnter() {
  try {
    if (isIE()) {
      // eslint-disable-next-line no-new
      new ActiveXObject(CtlName);
    } else {
      var powerEnterPlugin = navigator.plugins[PowerEnter_ProductDescription];
      if (powerEnterPlugin == null) {
        return false;
      }
    }
  } catch (e) {
    return false;
  }
  return true;
}
function getDownLoadPath() {
  if (navigator.platform == 'Win32' || navigator.platform == 'Windows' || navigator.platform == 'Win64') {
    return WIN_SETUP_PATH;
    // eslint-disable-next-line brace-style
  }
  // Windows
  else if (
    navigator.platform == 'Mac68K' ||
    navigator.platform == 'MacPPC' ||
    navigator.platform == 'Macintosh' ||
    navigator.platform == 'MacIntel'
  ) {
    return MAC_SETUP_PATH;
  } // MAC

  return WIN_SETUP_PATH;
}

function getObjVersion() {
  if (navigator.platform == 'Win64' || navigator.cpuClass == 'x64') {
    if (isIE()) return WIN_64_ACTIVEX_VERSION;
    // Windows系统下64位控件版本
    else return WIN_PLUGIN_VERSION; // Windows系统下插件版本
  } else if (navigator.platform == 'Win32' || navigator.platform == 'Windows') {
    if (isIE()) return WIN_32_ACTIVEX_VERSION;
    // Windows系统下32位控件版本
    else return WIN_PLUGIN_VERSION; // Windows系统下插件版本
  } else if (
    navigator.platform == 'Mac68K' ||
    navigator.platform == 'MacPPC' ||
    navigator.platform == 'Macintosh' ||
    navigator.platform == 'MacIntel'
  ) {
    return MAC_PLUGIN_VERSION; // Mac系统下插件版本
  }
  return '';
}

function isIE() {
  if (navigator.appName == 'Microsoft Internet Explorer' || navigator.userAgent.indexOf('Trident') > 0) {
    return true;
  } else return false;
}

function checkBrowser() {
  var _broswer = {};
  var ua = navigator.userAgent.toLocaleLowerCase();
  var browserType = null;
  if (ua.match(/msie/) != null || ua.match(/trident/) != null) {
    browserType = 'IE';
    browserVersion = ua.match(/msie ([\d.]+)/) != null ? ua.match(/msie ([\d.]+)/)[1] : ua.match(/rv:([\d.]+)/)[1];
    _broswer.name = 'IE';
    _broswer.core = 'IE';
    _broswer.version = browserVersion;
  } else if (ua.match(/firefox/) != null) {
    browserVersion = ua.match(/firefox\/([\d.]+)/)[1];
    _broswer.name = 'Firefox';
    _broswer.core = 'Firefox';
    _broswer.version = browserVersion;
  } else if (ua.match(/opera/) != null) {
    _broswer.name = 'opera';
    _broswer.core = 'opera';
  } else if (ua.match(/chrome/) != null) {
    var reChorme = new RegExp('chrome/(\\d+\\.\\d+(?:\\.\\d+\\.\\d+))?');
    reChorme.test(ua);
    _broswer.version = parseFloat(RegExp['$1']);
    _broswer.core = 'chrome';
    var is360 = _mime('type', 'application/vnd.chromium.remoting-viewer');

    // eslint-disable-next-line no-inner-declarations
    function _mime(option, value) {
      var mimeTypes = navigator.mimeTypes;
      for (var mt in mimeTypes) {
        if (mimeTypes[mt][option] == value) {
          return true;
        }
      }
      return false;
    }
    var isEdge = ua.indexOf('edge') > -1;
    if (isEdge) {
      browserType = 'edge';
    } else if (is360) {
      browserType = '360极速';
    } else {
      browserType = 'chrome';
    }
    _broswer.name = browserType;
  } else if (ua.match(/safari/) != null) {
    browserType = 'Safari';
  }
  return _broswer;
}

function isSupportBrowser() {
  var result1 = checkBrowser();
  if (result1.name == '360极速') {
    return false;
  }
  var powerEnterPlugin = navigator.plugins[PowerEnter_ProductDescription];
  if (powerEnterPlugin == null) {
    if (result1.name == 'edge') return false;
    else if (result1.name == 'chrome' && result1.version >= 43) return false;
    else if (result1.name == 'Firefox' && result1.version >= 47) return false;
    else if (result1.name == 'opera') return false;
    else return true;
  } else {
    return true;
  }
}

function GetResponseData(strPortNb, strMethod, strParam) {
  axios.jsonp('https://powerservice.csii.com.cn:50876/' + strMethod + '?' + strParam).then((x) => {
    var page = '';
    var id;
    // eslint-disable-next-line no-useless-escape
    if (strParam) {
      // eslint-disable-next-line no-useless-escape
      if (/&editID=(.*)\&/.test(strParam)) {
        id = RegExp.$1.split('&')[0];
      }
      // eslint-disable-next-line no-useless-escape
      if (/pageID=(.*)\&/.test(strParam)) {
        page = RegExp.$1.split('&')[0];
      }
    }
    ajaxSuccess(x, strMethod, strPortNb, id, page);
  });
}

function ajaxSuccess(x, strMethod, strPortNb, id, page) {
  if (strMethod == 'getValueLen') {
    var passwordLen = document.querySelector('#' + x.id).value.length;
    if (passwordLen != x.pwLen) changePass(x.pwLen, x.id, x.degree, id);

    if (g_stopSendRequest == 0) {
      if (document.querySelector('#' + x.id).getAttribute('isbusy') == 1) {
        var pageId = page || 'loginPage';
        GetPasswordLen(pageId, x.id);
      }
    }
  }
}

function GetResponseDataByDtd(isAsyns, strPortNb, strMethod, strParam, dtd) {
  axios
    .jsonp('https://powerservice.csii.com.cn:50876/' + strMethod + '?' + strParam)
    .then((x) => {
      ajaxSuccessByDtd(x, strMethod, strPortNb, dtd);
    })
    .catch((jqXHR, textStatus, errorThrown) => {
      console.error('ajaxErrorByDtd:', jqXHR);
      ajaxErrorByDtd(jqXHR, textStatus, errorThrown, strMethod, dtd);
    });
}

function ajaxSuccessByDtd(x, strMethod, strPortNb, dtd) {
  // let x = JSON.parse(x.data.split('(')[1].split(')')[0]);
  if (strMethod == 'initDll') {
    g_portNb = strPortNb;
    g_input_connectFlag = 1;
    g_connectTimes = 0;
    if (x.version < WIN_POWERSERVICE_VERSION || x.version == undefined) {
      g_input_connectFlag = 2;
    }
    setTimeout(() => {
      createinput();
    }, 200);
    dtd.resolve();
  } else if (strMethod == 'initPSDll') {
    g_portNb = strPortNb;
    g_sign_connectFlag = 1;
    g_connectTimes = 0;
    if (x.version < WIN_POWERSERVICE_VERSION || x.version == undefined) {
      g_sign_connectFlag = 2;
    }
    dtd.resolve();
  } else if (strMethod == 'getValue') {
    encPass = x.responseData;
    getSM2input();
    dtd.resolve();
  } else if (strMethod == 'comparePassword') {
    passType = x.responseData;
    dtd.resolve();
  } else if (strMethod == 'getMFM') {
    encMFM = x.responseData;
    // console.log("getMFM:" + encMFM);
    dtd.resolve();
  } else if (strMethod == 'GetCertList') {
    certlist = x.responseData;
    dtd.resolve();
  } else if (strMethod == 'GetSignCert') {
    serviceSignCert = x.responseData;
    // console.log("GetSignCert:" + serviceSignCert);
    dtd.resolve();
  } else if (strMethod == 'GetSignData') {
    serviceSignData = x.responseData;
    // serviceErrorMsg = x.err;
    // console.log("GetSignData:" + serviceSignData);
    dtd.resolve();
  } else if (strMethod == 'GetLastError') {
    serviceLastError = x.responseData;
    // console.log("GetLastError:" + serviceLastError);
    dtd.resolve();
  }
}

function ajaxErrorByDtd(jqXHR, textStatus, errorThrown, strMethod, dtd) {
  if (strMethod == 'initDll') {
    g_connectTimes++;
    if (g_connectTimes > 1) {
      // console.log("安全输入控件初始化失败，请重新下载并安装安全输入控件。");
      dtd.resolve();
    }
  }
}

function changePass(len, editID, degree, id) {
  var val = '';
  if (len != document.getElementById(editID).value.length) {
    for (var i = 0; i < len; i++) val += '●';
    document.getElementById(editID).value = val;
  }
  OnEventDegree(degree, id);
}

function GetPasswordLen(pageID, editID) {
  var passwordLen = document.getElementById(editID).value.length;
  var startParam = 'pageID=' + pageID + '&editID=' + editID + '&passwordLen=' + passwordLen;

  GetResponseData(g_portNb, 'getValueLen', startParam);
}

function getLocalService(
  pageID,
  editID,
  minLen,
  maxLen,
  contentType,
  rule,
  encryptType,
  appKeyIndex,
  appKey,
  encKeyIndex,
  encKey,
  strPlaceholder,
  encKeyAlg,
  sm2EncType,
  pwdObj,
) {
  var startParam =
    'pageID=' +
    pageID +
    '&editID=' +
    editID +
    '&minLen=' +
    minLen +
    '&maxLen=' +
    maxLen +
    '&rule=' +
    rule +
    '&encryptType=' +
    encryptType +
    '&appKeyIndex=' +
    appKeyIndex +
    '&appKey=' +
    appKey +
    '&encKeyIndex=' +
    encKeyIndex +
    '&encKey=' +
    encKey +
    '&contentType=' +
    contentType +
    '&encKeyAlg=' +
    encKeyAlg +
    '&sm2EncType=' +
    sm2EncType +
    '&calcFactor=' +
    (pwdObj.calcFactor ? pwdObj.calcFactor : '0');

  GetResponseData(g_portNb, 'initDll', startParam);
  var result = {
    input: '',
    script: '',
  };
  var style = 'width:' + pwdObj.width + 'px;height:' + pwdObj.height + 'px;border:none;outline:none;';
  result.input =
    '<input style=' +
    style +
    ' type="password" id="' +
    editID +
    '"  readonly  onselectstart="return false" onselect="return false" onkeyup="return false" onkeypress="return false" autocomplete="off" isbusy="0" placeholder="' +
    strPlaceholder +
    '"></input>';
  // onkeydown="return false"
  var scriptHtml =
    'document.getElementById("' +
    editID +
    '").onfocus=function(){' +
    'document.getElementById("' +
    editID +
    '").removeAttribute("readonly");' +
    'document.getElementById("' +
    editID +
    '").setAttribute("isbusy",1);' +
    'g_stopSendRequest=0;' +
    'var startParam = "pageID=' +
    pageID +
    '&editID=' +
    editID +
    '";' +
    'GetResponseData(' +
    g_portNb +
    ', "startSafeInput", startParam);' +
    'GetPasswordLen("' +
    pageID +
    '","' +
    editID +
    '");' +
    '};' +
    'document.getElementById("' +
    editID +
    '").onblur=function(){' +
    'document.getElementById("' +
    editID +
    '").setAttribute("isbusy",0);' +
    'document.getElementById("' +
    editID +
    '").setAttribute("readonly",true);' +
    'g_stopSendRequest=1;' +
    'GetResponseData(' +
    g_portNb +
    ', "stopSafeInput");' +
    '};';
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.innerHTML = scriptHtml;
  result.script = script;
  return result;
}

// eslint-disable-next-line no-unused-vars
function getLocalMFMService(
  pageID,
  editID,
  minLen,
  maxLen,
  contentType,
  rule,
  encryptType,
  appKeyIndex,
  appKey,
  encKeyIndex,
  encKey,
  // eslint-disable-next-line no-unused-vars
  strPlaceholder,
) {
  var startParam =
    'pageID=' +
    pageID +
    '&editID=' +
    editID +
    '&minLen=' +
    minLen +
    '&maxLen=' +
    maxLen +
    '&rule=' +
    rule +
    '&encryptType=' +
    encryptType +
    '&appKeyIndex=' +
    appKeyIndex +
    '&appKey=' +
    appKey +
    '&encKeyIndex=' +
    encKeyIndex +
    '&encKey=' +
    encKey +
    '&contentType=' +
    contentType;

  GetResponseData(g_portNb, 'initDll', startParam);
}

// eslint-disable-next-line no-unused-vars
function doAdd(editID) {
  if (typeof editID === 'object') {
    editID = editID.id;
  }
  // 获取对象
  var powerpass = document.getElementById('editID');
  if (editID == 'forgetPwdUserId') {
    var forget = document.getElementById('forgetPwdUserId');
    addEvent(forget, 'EventDegree', forgetPwdUserIdFunc);
  } else if (editID == 'forgetPwdUser') {
    // eslint-disable-next-line no-redeclare
    var forget = document.getElementById('forgetPwdUser');
    addEvent(forget, 'EventDegree', forgetPwdUserFunc);
  } else if (editID == 'forgetPwdUserIdAgain') {
    // eslint-disable-next-line no-redeclare
    var forget = document.getElementById('forgetPwdUserIdAgain');
    addEvent(powerpass, 'EventDegree', forgetPwdUserIdAgainFunc);
  } else if (editID == 'forgetPwdUserAgain') {
    // eslint-disable-next-line no-redeclare
    var forget = document.getElementById('forgetPwdUserAgain');
    addEvent(powerpass, 'EventDegree', forgetPwdUserAgainFunc);
  } else {
    addEvent(powerpass, 'EventDegree', OnEventDegree);
  }
  // 添加Password控件的回车事件，如果收到此事件，则触发OnPassEventReturn()函数
  // addEvent(powerpass, "EventReturn", OnPassEventReturn);
  // 添加Password控件的Tab事件，如果收到此事件，则触发OnPassEventTab()函数
  // addEvent(powerpass, "EventTab", OnPassEventTab);
  // 添加Password控件的密码强弱度事件，如果收到此事件，则触发OnEventDegree(arg1)函数
}

function forgetPwdUserIdFunc(arg1) {
  // eslint-disable-next-line no-unused-vars
  var degree = '';
  if (arg1 == 'W') {
    degree = '弱';
  } else if (arg1 == 'M') {
    degree = '中';
  } else if (arg1 == 'S') {
    degree = '强';
  }
  for (var i = 0; i < vmObj.pwdObj.length; i++) {
    if (vmObj.pwdObj[i].id == 'forgetPwdUserId' && vmObj.pwdObj[i].showDegree) {
      vmObj.pwdObj[i].pwdDegree = arg1;
      vmObj.$forceUpdate();
    }
  }
}

function forgetPwdUserFunc(arg1) {
  // eslint-disable-next-line no-unused-vars
  var degree = '';
  if (arg1 == 'W') {
    degree = '弱';
  } else if (arg1 == 'M') {
    degree = '中';
  } else if (arg1 == 'S') {
    degree = '强';
  }
  for (var i = 0; i < vmObj.pwdObj.length; i++) {
    if (vmObj.pwdObj[i].id == 'forgetPwdUser' && vmObj.pwdObj[i].showDegree) {
      vmObj.pwdObj[i].pwdDegree = arg1;
      vmObj.$forceUpdate();
    }
  }
}

function forgetPwdUserIdAgainFunc(arg1) {
  // eslint-disable-next-line no-unused-vars
  var degree = '';
  if (arg1 == 'W') {
    degree = '弱';
  } else if (arg1 == 'M') {
    degree = '中';
  } else if (arg1 == 'S') {
    degree = '强';
  }
  for (var i = 0; i < vmObj.pwdObj.length; i++) {
    if (vmObj.pwdObj[i].id == 'forgetPwdUserIdAgain' && vmObj.pwdObj[i].showDegree) {
      vmObj.pwdObj[i].pwdDegree = arg1;
      vmObj.$forceUpdate();
    }
  }
}

function forgetPwdUserAgainFunc(arg1) {
  // eslint-disable-next-line no-unused-vars
  var degree = '';
  if (arg1 == 'W') {
    degree = '弱';
  } else if (arg1 == 'M') {
    degree = '中';
  } else if (arg1 == 'S') {
    degree = '强';
  }
  for (var i = 0; i < vmObj.pwdObj.length; i++) {
    if (vmObj.pwdObj[i].id == 'forgetPwdUserAgain' && vmObj.pwdObj[i].showDegree) {
      vmObj.pwdObj[i].pwdDegree = arg1;
      vmObj.$forceUpdate();
    }
  }
}

function addEvent(obj, name, func) {
  obj.addEventListener(name, func, false);
}
// eslint-disable-next-line no-unused-vars
function OnPassEventReturn() {
  // 在收到Password控件上的回车事件时，将焦点放在id为login的标签上。
  document.getElementById('powerpass1').focus();
}

// eslint-disable-next-line no-unused-vars
function OnPassEventTab() {
  // 在收到Password控件上的Tab事件时，将焦点放在id为login的标签上。
  document.getElementById('code').focus();
}

function OnEventDegree(arg1, id) {
  // console.log(event);
  // eslint-disable-next-line no-unused-vars
  var degree = '';
  if (arg1 == 'W') {
    degree = '弱';
  } else if (arg1 == 'M') {
    degree = '中';
  } else if (arg1 == 'S') {
    degree = '强';
  }
  for (var i = 0; i < vmObj.pwdObj.length; i++) {
    if (vmObj.pwdObj[i].id == id && vmObj.pwdObj[i].showDegree) {
      // console.log(id + "密码强度:" + degree)
      vmObj.pwdObj[i].pwdDegree = arg1;
      vmObj.$forceUpdate();
    }
  }
  // window.document.getElementById("EEE").innerHTML = "密码强度:" + degree;
}

// 获取国密签名证书DN
function getCertDN() {
  return new Promise((resolve, reject) => {
    let dtd = defer();
    Promise.all([GetServiceCertList(dtd), dtd])
      .then(function() {
        setTimeout(() => {
          console.log(`[csii sign cert LIST]:`, certlist);
          if (certlist == 'E:1000' || certlist == '') {
            reject(certlist);
            return;
          }
          // 这块处理注意下，有时RSA证书也会出现在certlist中，按照实际情况只取sm2证书信息
          certValue = certlist.split(';').shift();
          // DN一般CFCA插件提供的插件有接口可以获取，但是那个插件的兼容性太差，所以这里我们自己拼接一下，就是证书的CN信息加上后缀
          let certDN = certValue.split(',').shift() + ', OU=Organizational-3, OU=Local RA, O=CFCA TEST OCA31, C=CN';
          getCertSN();
          resolve(certDN);
        }, 500);
      })
      .catch((error) => {
        reject(error);
      });
  });
}

// 获取证书SN
function getCertSN() {
  // 这块也注意下，certValue中有的会带SN=这种字符串，有的没有，但是一般certVal都是由CN和SN用逗号拼接，所以这里后面的字符串就可以了
  let newCertlist = certValue.split(',');
  certSN = newCertlist.pop().replace(/SN=/g, '');
  return certSN;
}

// 获取证书base64值
function getBase64Cert() {
  return new Promise((resolve, reject) => {
    if (!isSupportBrowser()) {
      let dtd = defer();
      Promise.all([GetServiceSignCert(certSN, HASH_ALG, dtd)]).then(function() {
        setTimeout(function() {
          if (serviceSignCert == 'E:1000') {
            reject('证书信息获取错误，请刷新页面重试');
          } else {
            resolve(serviceSignCert);
          }
        }, 500);
      });
    } else {
      let psObj = document.getElementById('powersign');
      psObj.CN = certSN;
      psObj.HashAlgorithm = HASH_ALG;
      resolve(psObj.SignCert());
    }
  });
}

// 数据签名
function getSignData(originData, todo, errtodo) {
  if (!isSupportBrowser()) {
    // originData = "<?xml version=\"1.0\" encoding=\"utf-8\"?><T><D><M><k>付款人账号：</k><v>6236431800000016143</v></M><M><k>收款人账号：</k><v>6216900200002549</v></M><M><k>收款人姓名：</k><v>令牌测试一</v></M><M><k>交易金额：</k><v>1</v></M></D></T>";
    let dtd = defer();
    Promise.all([GetServiceSignData(certSN, HASH_ALG, originData, dtd)]).then(function() {
      setTimeout(function() {
        console.log(`powersign 签名密文:${serviceSignData}`);
        if (serviceSignData && serviceSignData.indexOf('<?xml') != -1) {
          todo(serviceSignData);
        } else if (serviceSignData == 'E:1000') {
          errtodo && errtodo('签名失败：E:1000');
        } else {
          errtodo && errtodo('签名失败');
        }
      }, 500);
    });
  } else {
    let psObj = document.getElementById('powersign');
    psObj.CN = certSN;
    psObj.HashAlgorithm = HASH_ALG;
    psObj.SignData = originData; //待签名数据
    let signData = psObj.getSignData();
    // console.log(`[csii sign cert signData]:${signData}`);
    if (signData && signData.indexOf('<?xml') != -1) {
      todo(signData);
    } else if (signData == 'E:1000') {
      errtodo && errtodo('签名失败：E:1000');
    } else {
      errtodo && errtodo('签名失败');
    }
  }
}

window.onbeforeunload = onbeforeunload_handler;

function onbeforeunload_handler() {
  var powerEnterPlugin = navigator.plugins[PowerEnter_ProductDescription];
  if (powerEnterPlugin == null) {
    var result1 = checkBrowser();
    if (result1.name == 'chrome' && result1.version >= 45) {
      GetResponseData(g_portNb, 'stopSafeInput');
      // return "";
    } else {
      GetResponseData(g_portNb, 'stopSafeInput');
    }
  }
  // return null;
}
function defer() {
  const deferred = {};
  const promise = new Promise((resolve, reject) => {
    deferred.resolve = resolve;
    deferred.reject = reject;
  });
  deferred.promise = () => {
    return promise;
  };
  return deferred;
}

export {
  powerConfig,
  powerProter,
  createPwdObject,
  passwordCheck,
  writePluginObject,
  writeObject,
  PEGetPluginObject,
  PEGetObject,
  getPassObject,
  getUtilObject,
  getSignObject,
  writeUtilObject,
  getPassInput,
  getMFMInput,
  CheckServicePass,
  GetPassword,
  GetServiceCertList,
  GetServiceSignCert,
  GetServiceSignData,
  GetServiceLastError,
  PEGetElement,
  getPEXSetupUrl,
  getLocalObjVersion,
  isRegisteredPowerEnter,
  getDownLoadPath,
  getObjVersion,
  isIE,
  checkBrowser,
  isSupportBrowser,
  GetResponseData,
  ajaxSuccess,
  GetResponseDataByDtd,
  ajaxSuccessByDtd,
  ajaxErrorByDtd,
  changePass,
  // init,
  // initPowerSign,
  GetPasswordLen,
  getLocalService,
  getLocalMFMService,
  doAdd,
  forgetPwdUserIdFunc,
  forgetPwdUserFunc,
  forgetPwdUserIdAgainFunc,
  forgetPwdUserAgainFunc,
  addEvent,
  OnPassEventReturn,
  OnPassEventTab,
  OnEventDegree,
  onbeforeunload_handler,
  getCertDN,
  getBase64Cert,
  getSignData,
  getCertSN,
};
